//
//  ISHomeViewController.m
//  iPhoneSafety
//
//  Created by dlon 2018/12/30.
//  Copyright © 2018年 com.li.ding. All rights reserved.
//

#import "ISHomeViewController.h"
#import "ISHomeCollectionViewCell.h"
#import "NWLazyProperty.h"
#import <Masonry/Masonry.h>
#import "UIColor+NWHex.h"
#import "ISGradientLayerView.h"
#import "ISOpenDeatilViewController.h"
#import "CustomNavigationViewController.h"
#import <libextobjc/EXTScope.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import "ISStopProtectViewController.h"
#import "ISSettingViewController.h"
#import "ISSafetyAlarmCameraManager.h"

#import "ISPasswordViewController.h"
#import "ISSafetyAlarmMailManager.h"
#import <AVFoundation/AVFoundation.h>

#import "ISSafetyGuideViewController.h"

@interface ISHomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) ISGradientLayerView *headView;
@property (nonatomic, strong) UIButton *openButton;
@property (nonatomic, strong) ISGradientLayerView *openButtonBottom;
@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, assign) CGFloat lastCollectionViewOffset;
@end

@implementation ISHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_navbar_setting_n"] style:UIBarButtonItemStyleDone target:self action:@selector(setting)]];
    
    UIImageView *imageView = [UIImageView new];
    imageView.image = [UIImage imageNamed:@"img_navbar_title_home"];
    [self.navigationItem setTitleView:imageView];
    
    [self.view addSubview:self.headView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.openButton];
    [self.view addSubview:self.openButtonBottom];
    
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.collectionView.mas_top).offset(100.f);
    }];
    
    @weakify(self)
    [self.openButton bk_addEventHandler:^(id sender) {
        @strongify(self)
        
        NSString *pwdStr = [ISPassword pwd];
        if (pwdStr.length == 0) {
            ISPasswordViewController *pwd = [ISPasswordViewController new];
            pwd.type = ISPasswordViewControllerTypeNew;
            [self.navigationController pushViewController:pwd animated:YES];
            return;
        }
        
        if ([[ISSafetyAlarmMamanger sharedInstance] startMonitoringWithStrategyStatus]) {
            ISStopProtectViewController *vc = [ISStopProtectViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
       
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self loadData];

    [[NSNotificationCenter defaultCenter] addObserverForName:kISSafetyAlarmStateAlarmingNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        @strongify(self)
        if (![ISPassword isShow]) {
            ISPasswordViewController *vc = [ISPasswordViewController new];
            vc.type = ISPasswordViewControllerTypeVerify;
            [self.navigationController presentViewController:vc animated:NO completion:nil];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"kISSafetyGuideShown"]) {
        ISSafetyGuideViewController *vc = [[ISSafetyGuideViewController alloc] init];
        [self presentViewController:vc animated:YES completion:nil];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kISSafetyGuideShown"];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.frame = CGRectMake(0, self.view.safeAreaInsets.top + 15, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - self.view.safeAreaInsets.top - 15);
        self.openButton.frame = CGRectMake((CGRectGetWidth(self.view.frame) - 240.f)/2.f, CGRectGetHeight(self.view.frame) - 70.f - self.view.safeAreaInsets.bottom, 240.f,70.f);
        if (self.view.safeAreaInsets.bottom > 0) {
            self.openButtonBottom.frame = CGRectMake(0, CGRectGetMaxY(self.openButton.frame), CGRectGetWidth(self.view.frame), self.view.safeAreaInsets.bottom);
        }
    } else {
        self.collectionView.frame = CGRectMake(0, 79.f, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 79);
        self.openButton.frame = CGRectMake((CGRectGetWidth(self.view.frame) - 240.f)/2.f, CGRectGetHeight(self.view.frame) - 70.f, 240.f, 70);
    }
    
}

- (void)loadData {
    [self.list removeAllObjects];

    CGFloat partHeight = (([UIScreen mainScreen].bounds.size.width - 12.f) / 2.f) / (182.f / 234.f);
    //口袋防盗
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISHomeCollectionViewCell";
        dict[@"strategy"] = @(ISSafetyAlarmStrategyPocket);
        dict[@"height"] = @(partHeight);
        
        dict[@"img"] = @"img_home_card_pocket";
        dict[@"des"] = @"当手机被拿出口袋时会立即响起警报";
        dict[@"title"] = @"口袋防盗";
        dict[@"img_banner"] = @"img_detail_pocket_banner";
        dict[@"bg_img"] = @"img_detail_pocket_bg";
        dict[@"is_on"] = @([[ISSafetyAlarmMamanger sharedInstance] onOrCloseWithStrategy:ISSafetyAlarmStrategyPocket]);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [[ISSafetyAlarmMamanger sharedInstance] onOrCloseStrategy:ISSafetyAlarmStrategyPocket on:value];
        };
        [self.list addObject:dict];
    }

    //桌面
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISHomeCollectionViewCell";
        dict[@"strategy"] = @(ISSafetyAlarmStrategyDesk);
        dict[@"height"] = @(partHeight);
        
        dict[@"img"] = @"img_home_card_desktop";
        dict[@"des"] = @"当手机离开桌面时会立即响起警报";
        dict[@"title"] = @"桌面防盗";
        dict[@"img_banner"] = @"img_detail_desktop_banner";
        dict[@"bg_img"] = @"img_detail_desktop_bg";
        dict[@"is_on"] = @([[ISSafetyAlarmMamanger sharedInstance] onOrCloseWithStrategy:ISSafetyAlarmStrategyDesk]);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [[ISSafetyAlarmMamanger sharedInstance] onOrCloseStrategy:ISSafetyAlarmStrategyDesk on:value];
        };
        [self.list addObject:dict];
    }

    //充电防盗
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISHomeCollectionViewCell";
        dict[@"strategy"] = @(ISSafetyAlarmStrategyCharging);
        dict[@"height"] = @(partHeight);
        
        dict[@"img"] = @"img_home_card_charge";
        dict[@"des"] = @"当手机被断开充电时会立即响起警报";
        dict[@"title"] = @"充电防盗";
        dict[@"img_banner"] = @"img_detail_charge_banner";
        dict[@"bg_img"] = @"img_detail_charge_bg";
        dict[@"is_on"] = @([[ISSafetyAlarmMamanger sharedInstance] onOrCloseWithStrategy:ISSafetyAlarmStrategyCharging]);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [[ISSafetyAlarmMamanger sharedInstance] onOrCloseStrategy:ISSafetyAlarmStrategyCharging on:value];
        };
        [self.list addObject:dict];
    }

    
    //飞行防盗
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISHomeCollectionViewCell";
        dict[@"strategy"] = @(ISSafetyAlarmStrategyAirplan);
        dict[@"height"] = @(partHeight);
        
        dict[@"img"] = @"img_home_card_airplane";
        dict[@"des"] = @"当手机开启飞行模式时会立即响起警报";
        dict[@"title"] = @"飞行防盗";
        dict[@"img_banner"] = @"img_detail_airplane_banner";
        dict[@"bg_img"] = @"img_detail_airplane_bg";
        dict[@"is_on"] =  @([[ISSafetyAlarmMamanger sharedInstance] onOrCloseWithStrategy:ISSafetyAlarmStrategyAirplan]);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [[ISSafetyAlarmMamanger sharedInstance] onOrCloseStrategy:ISSafetyAlarmStrategyAirplan on:value];
        };
        [self.list addObject:dict];
    }

    //耳机防盗
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISHomeCollectionViewCell";
        dict[@"strategy"] = @(ISSafetyAlarmStrategyHeadset);
        dict[@"height"] = @(partHeight);
        
        dict[@"img"] = @"img_home_card_earphone";
        dict[@"des"] = @"当手机耳机被拔出时会立即响起警报";
        dict[@"title"] = @"耳机防盗";
        dict[@"img_banner"] = @"img_detail_earphone_banner";
        dict[@"bg_img"] = @"img_detail_earphone_bg";
        dict[@"is_on"] = @([[ISSafetyAlarmMamanger sharedInstance] onOrCloseWithStrategy:ISSafetyAlarmStrategyHeadset]);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [[ISSafetyAlarmMamanger sharedInstance] onOrCloseStrategy:ISSafetyAlarmStrategyHeadset on:value];
        };
        [self.list addObject:dict];
    }

    //空白行
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"UICollectionViewCell";
        dict[@"height"] = @(partHeight);
        [self.list addObject:dict];
    }

    //空白行
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"UICollectionViewCell";
        dict[@"height"] = @(90.f);
        [self.list addObject:dict];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - action
- (void)setting {
    ISSettingViewController *setting = [ISSettingViewController new];
    [self.navigationController pushViewController:setting animated:YES];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    NSString *type = viewModel[@"type"];
    if ([type isEqualToString:@"ISHomeCollectionViewCell"]) {
        ISOpenDeatilViewController *vc = [ISOpenDeatilViewController new];
        vc.titleLabel.text = viewModel[@"title"];
        vc.desLabel.text = viewModel[@"des"];
        vc.desImgView.image = [UIImage imageNamed:viewModel[@"img_banner"]];
        vc.bgImgView.image = [UIImage imageNamed:viewModel[@"bg_img"]];
        vc.strategy = [viewModel[@"strategy"] unsignedIntegerValue];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    NSString *type = viewModel[@"type"];
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:type forIndexPath:indexPath];
    
    if ([type isEqualToString:@"ISHomeCollectionViewCell"]) {
        ISHomeCollectionViewCell *homeCell = (ISHomeCollectionViewCell *)cell;
        homeCell.desLabel.text = viewModel[@"des"];
        homeCell.titleLabel.text = viewModel[@"title"];
        homeCell.imgView.image = [UIImage imageNamed:viewModel[@"img"]];
        homeCell.switchView.on = [viewModel[@"is_on"] boolValue];
        homeCell.actionBlock = viewModel[@"actionBlock"];
    } else {
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
    }
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.list.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    return CGSizeMake(floor(CGRectGetWidth(collectionView.frame) / 2.f - 6.f), [viewModel[@"height"] doubleValue]);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.lastCollectionViewOffset + 10.f) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    } else if(scrollView.contentOffset.y < self.lastCollectionViewOffset - 10.f || scrollView.contentOffset.y <= 0.f) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    self.lastCollectionViewOffset = scrollView.contentOffset.y;
}

#pragma mark - set & get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 6, 0, 6);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [_collectionView registerClass:[ISHomeCollectionViewCell class] forCellWithReuseIdentifier:@"ISHomeCollectionViewCell"];
        
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
        
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _collectionView;
}

NWLazyPropertyWithInit(NSMutableArray, list, {})

NWLazyPropertyWithInit(UIButton, openButton, {
    [_openButton setTitle:@"开启保护" forState:UIControlStateNormal];
    [_openButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _openButton.titleLabel.font = [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium];
    _openButton.contentEdgeInsets = UIEdgeInsetsMake(14, 0, 0, 0);
    _openButton.adjustsImageWhenHighlighted = NO;
    [_openButton setBackgroundImage:[UIImage imageNamed:@"img_home_buttong_bg"] forState:UIControlStateNormal];
})

- (ISGradientLayerView *)openButtonBottom {
    if (!_openButtonBottom) {
        _openButtonBottom = [ISGradientLayerView new];
        CAGradientLayer *layer = (CAGradientLayer *)_openButtonBottom.layer;
        
        layer.startPoint = CGPointMake(0, 0);
        layer.endPoint = CGPointMake(1, 0);
        
        layer.colors = @[(id)[UIColor nw_colorWithHex:0x00A7FD].CGColor,(id)[UIColor nw_colorWithHex:0x00A7FD].CGColor];
    }
    return _openButtonBottom;
}

- (ISGradientLayerView *)headView {
    if (!_headView) {
        _headView = [ISGradientLayerView new];
        _headView.backgroundColor = [UIColor redColor];
        
        CAGradientLayer *layer = (CAGradientLayer *)_headView.layer;
        
        layer.startPoint = CGPointMake(0, 0);
        layer.endPoint = CGPointMake(1, 0);
        
        layer.colors = @[(id)[UIColor nw_colorWithHex:0x1270FC].CGColor,(id)[UIColor nw_colorWithHex:0x00A7FD].CGColor];
    }
    return _headView;
}

@end
